package com.ruge.sorm.core;

import com.ruge.sorm.bean.Configuration;
import com.ruge.sorm.util.PropertiesUtils;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 根据配置信息，维持连接对象的管理（增加连接池功能）
 *
 * @author admin
 * @version 2023/10/21 10:15
 **/
public class DBManager {
    private static Configuration conf;

    static { // 静态代码块
        // 加载指定的资源文件
        String driverName = PropertiesUtils.getString("spring.datasource.driver-class-name");
        String url = PropertiesUtils.getString("spring.datasource.url");
        String user = PropertiesUtils.getString("spring.datasource.username");
        String password = PropertiesUtils.getString("spring.datasource.password");

        conf = new Configuration();
        conf.setDriver(driverName);
        conf.setPoPackage("poPackage");
        conf.setPwd(password);
        conf.setSrcPath("srcPath");
        conf.setUser(user);
        conf.setUsingDB("usingDB");
        conf.setUrl(url);

    }

    public static Connection getConnection() {
        try {
            Class.forName(conf.getDriver());
            // 目前直接建立连接，后期增加连接池处理，提高效率！
            return DriverManager.getConnection(conf.getUrl(), conf.getUser(), conf.getPwd());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void close(ResultSet resultSet, Statement sts, Connection conn) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if (sts != null) {
                sts.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void close(Statement sts, Connection conn) {

        try {
            if (sts != null) {
                sts.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    public static void close(Connection conn) {

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    /**
     * 返回Configuration对象
     *
     * @return
     */
    public static Configuration getConf() {
        return conf;
    }
}
